#include "AddConstructWidget.h"
#include "ui_AddConstructWidget.h"
#include "../database/DatabaseManager.h"
#include <QMessageBox>

AddConstructWidget::AddConstructWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AddConstructWidget)
{
    ui->setupUi(this);
}

AddConstructWidget::~AddConstructWidget()
{
    delete ui;
}

void AddConstructWidget::init()
{
    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;

    if (!db.isOpen()) {
        qWarning() << "数据库未连接";
        return;
    }

    QSqlQuery q(db);
    // 如果列名是 code，请把 mould_code 改为 code
    q.prepare("SELECT id, mould_code FROM Mould ORDER BY mould_code COLLATE NOCASE");
    if (!q.exec()) {
        qWarning() << "查询失败:" << q.lastError().text();
        return;
    }
    QSignalBlocker blocker(ui->comboBox);
    ui->comboBox->clear();
    while (q.next()) {
        const int id = q.value(0).toInt();
        const QString name = q.value(1).toString();
        ui->comboBox->addItem(name, id);               // 文本显示 name，userData 存 id
    }

    // 可选：默认不选中任何项
    ui->comboBox->setCurrentIndex(-1);
}

void AddConstructWidget::on_comboBox_currentIndexChanged(int /*index*/)
{
    const int mouldId = ui->comboBox->currentData().toInt();

    // 侧板只读
    ui->lineEdit->setReadOnly(true);
    ui->lineEdit_1->setReadOnly(true);

    // 未选择任何模具：清空侧板与两个 block 下拉框
    if (mouldId <= 0) {
        ui->lineEdit->clear();
        ui->lineEdit_1->clear();
        {
            QSignalBlocker b2(ui->comboBox_2);
            QSignalBlocker b3(ui->comboBox_3);
            ui->comboBox_2->clear();
            ui->comboBox_3->clear();
            ui->comboBox_2->setCurrentIndex(-1);
            ui->comboBox_3->setCurrentIndex(-1);
        }
        return;
    }

    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;
    if (!db.isOpen()) {
        qWarning() << "数据库未连接";
        return;
    }

    // 1) 查询上/下侧板 code
    {
        QSqlQuery q(db);
        q.prepare(R"(
            SELECT COALESCE(su.sideplate_code, ''), COALESCE(sl.sideplate_code, '')
            FROM Mould m
            LEFT JOIN SidePlate su ON su.id = m.upper_id
            LEFT JOIN SidePlate sl ON sl.id = m.lower_id
            WHERE m.id = ?
        )");
        q.addBindValue(mouldId);

        if (!q.exec()) {
            qWarning() << "查询侧板失败:" << q.lastError().text();
        } else if (q.next()) {
            ui->lineEdit->setText(q.value(0).toString());   // 上侧板
            ui->lineEdit_1->setText(q.value(1).toString()); // 下侧板
        } else {
            ui->lineEdit->clear();
            ui->lineEdit_1->clear();
        }
    }

    // 2) 查询并填充该模具关联的 blocks -> comboBox_2 / comboBox_3
    {
        QSqlQuery q(db);
        q.prepare(R"(
            SELECT b.id, b.block_code
            FROM MouldBlock mb
            JOIN Block b ON b.id = mb.block_id
            WHERE mb.mould_id = ?
            ORDER BY b.block_code COLLATE NOCASE
        )");
        q.addBindValue(mouldId);

        if (!q.exec()) {
            qWarning() << "查询 Blocks 失败:" << q.lastError().text();
            // 清空以免显示旧数据
            QSignalBlocker b2(ui->comboBox_2);
            QSignalBlocker b3(ui->comboBox_3);
            ui->comboBox_2->clear();
            ui->comboBox_3->clear();
            ui->comboBox_2->setCurrentIndex(-1);
            ui->comboBox_3->setCurrentIndex(-1);
            return;
        }

        QSignalBlocker b2(ui->comboBox_2);
        QSignalBlocker b3(ui->comboBox_3);
        ui->comboBox_2->clear();
        ui->comboBox_3->clear();

        //（可选）添加一个空项作为“未选择”
        // ui->comboBox_2->addItem(tr("-- 请选择 --"), QVariant());
        // ui->comboBox_3->addItem(tr("-- 请选择 --"), QVariant());

        while (q.next()) {
            const int blockId = q.value(0).toInt();
            const QString blockCode = q.value(1).toString();
            ui->comboBox_2->addItem(blockCode, blockId);
            ui->comboBox_3->addItem(blockCode, blockId);
        }

        // 默认不选中（按需改成 0）
        ui->comboBox_2->setCurrentIndex(-1);
        ui->comboBox_3->setCurrentIndex(-1);
    }
}



void AddConstructWidget::on_pushButton_clicked()
{
    if (ui->comboBox_2->currentText().isEmpty() || ui->comboBox_3->currentText().isEmpty() || ui->lineEdit_4->text().isEmpty()) {
        QMessageBox::warning(this, tr("输入错误"), tr("输入框不能为空！"));
        return;
    }
    const int mouldId = ui->comboBox->currentData().toInt();
    const int upper = ui->comboBox_2->currentData().toInt();    // 上侧板活字块编码
    const int lower = ui->comboBox_3->currentData().toInt();  // 下侧板活字块编码
    const QString cid  = ui->lineEdit_4->text().trimmed();

    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;            // 用同一连接
    if (!db.isOpen()) { QMessageBox::critical(this, tr("错误"), tr("数据库未连接")); return; }
    // 3) 查询是否已存在
    int rowId = -1;
    QSqlQuery q(db);
    q.prepare("SELECT id FROM Construction WHERE construction_id = :cid AND mould_id = :mid LIMIT 1");
    q.bindValue(":cid", cid);
    q.bindValue(":mid", mouldId);
    if (!q.exec()) {
        QMessageBox::critical(this, tr("错误"), tr("查询失败：%1").arg(q.lastError().text()));
        return;
    }
    if (q.next())
        rowId = q.value(0).toInt();
    // 4) 事务
    if (!db.transaction()) { QMessageBox::critical(this, tr("错误"), tr("开启事务失败：%1").arg(db.lastError().text())); return; }

    bool ok = false;
    if (rowId > 0) {
        // 已存在 -> 询问是否覆盖
        auto ret = QMessageBox::question(
            this, tr("记录已存在"),
            tr("施工编号「%1」在该模具下已存在，是否覆盖？").arg(cid),
            QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
        if (ret == QMessageBox::No) { db.rollback(); return; }

        q.prepare(R"(
            UPDATE Construction
               SET upper_block_code = :up,
                   lower_block_code = :low
             WHERE id = :id
        )");
        q.bindValue(":up",  upper);
        q.bindValue(":low", lower);
        q.bindValue(":id",  rowId);
        ok = q.exec();
    } else {
        // 不存在 -> 新增
        q.prepare(R"(
            INSERT INTO Construction (construction_id, mould_id, upper_block_id, lower_block_id)
            VALUES (:cid, :mid, :up, :low)
        )");
        q.bindValue(":cid", cid);
        q.bindValue(":mid", mouldId);
        q.bindValue(":up",  upper);
        q.bindValue(":low", lower);
        ok = q.exec();
    }

    if (!ok) {
        db.rollback();
        // 如果你已经建立了 UNIQUE(construction_id, mould_id)，这里也能捕到冲突信息
        QMessageBox::critical(this, tr("错误"), tr("保存失败：%1").arg(q.lastError().text()));
        return;
    }

    if (!db.commit()) {
        db.rollback();
        QMessageBox::critical(this, tr("错误"), tr("提交失败：%1").arg(db.lastError().text()));
        return;
    }
}

